﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Threading;
using System.Net;
using System.IO;

namespace ProxyList
{
    class Checker
    {
        private string URL = String.Empty;
        private ProxyInfo Addr = null;
        private SendOrPostCallback Callback = null;

        private HttpWebRequest Req = null;

        public Checker(string TestURL, ProxyInfo Address, SendOrPostCallback CallbackFunc)
        {
            this.URL = TestURL;
            this.Addr = Address;
            this.Callback = CallbackFunc;
        }

        public void Stop()
        {
            Req.Abort();
        }

        public void Execute(AsyncOperation Operation)
        {
            new AsyncOperationInvoker(TestProxy).BeginInvoke(Operation, null, null);
        }

        private void TestProxy(object Obj)
        {
            AsyncOperation operation = Obj as AsyncOperation;

            Addr.Info = String.Empty;
            Addr.Answer = String.Empty;

            DateTime dt = DateTime.Now;
            try
            {
                //DoRequest(addr);
                Req = WebRequest.Create(URL) as HttpWebRequest;

                Req.Proxy = new WebProxy(Addr.Address, int.Parse(Addr.Port));
                Req.ContentType = "application/x-www-form-urlencoded";
                Req.Method = "HEAD";
                Req.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/532.0 (KHTML, like Gecko) Chrome/3.0.195.38 Safari/532.0";
                Req.Timeout = 10000;

                HttpWebResponse resp = Req.GetResponse() as HttpWebResponse;
                if (resp == null)
                    throw new Exception("нет ответа");

                foreach (string header in Enum.GetNames(typeof(HttpRequestHeader)))
                {
                    string s = resp.GetResponseHeader(header).Trim();
                    if (s == String.Empty) continue;
                    Addr.Answer += header + ": " + s + "\n";
                    // Addr.Info = "*";
                }

                using (StreamReader sr = new StreamReader(resp.GetResponseStream(), Encoding.GetEncoding("utf-8")))
                //using (StreamReader sr = new StreamReader(resp.GetResponseStream()))
                    sr.ReadToEnd();

                resp.Close();
            }
            catch (Exception e)
            {
                Addr.Info += e.Message;
            }
            finally
            {
                TimeSpan ts = DateTime.Now.Subtract(dt);
                int msec = ts.Minutes * 60000 + ts.Seconds * 1000 + ts.Milliseconds;
                Addr.MSec = msec.ToString();
            }

            // передать данные в UI.
            //operation.Post(callback, addr);
            operation.Post(Callback, Addr);
        }

    }
}
